package cn.jinjimi.app.main.widget.biz;

import android.content.Context;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.List;

import cn.jinjimi.app.R;
import cn.jinjimi.app.entity.LinkBean;
import cn.jinjimi.app.main.widget.EntranceView;
import cn.jinjimi.app.main.widget.FrescoImageView.FrescoImageView;
import cn.jinjimi.domain.data.dto.ConfigDTO;
import cn.jinjimi.domain.entity.Product;
import cn.jinjimi.framework.router.RouterHelper;

/**
 * @author zhenhua
 */
public class HomeEntranceView extends LinearLayout {

    private CountDown mCountDown;

    private final int[] rids = new int[]{
            R.id.entrance_1,
            R.id.entrance_2,
            R.id.entrance_3,
            R.id.entrance_4
    };

    public HomeEntranceView(Context context) {
        super(context);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).
                inflate(R.layout.view_home_entrances, this);
        setVisibility(View.GONE);
    }

    public void setData(List<LinkBean> data) {
        for (int i = 1, len = rids.length; i < len; i++) {
            LinkBean link = (i - 1 < data.size() ? data.get(i - 1) : null);
            render(rids[i], link);
        }
    }

    public void setData(ConfigDTO.LimitEntry limitEntry) {
        if (limitEntry.products != null && limitEntry.products.timeend * 1000 > System.currentTimeMillis()) {
            render(rids[0], limitEntry.entry, limitEntry.products);
        } else {
            render(rids[0], limitEntry.entry);
        }
    }

    /**
     * 显示带有倒计时的View
     * @param id
     * @param link
     * @param product
     */
    private void render(int id, final LinkBean link, final Product product) {
        //hide default entrance view.
        EntranceView view = findViewById(id);
        view.setVisibility(View.GONE);

        View v = findViewById(R.id.count_down_entrance);
        v.setVisibility(VISIBLE);
        v.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                RouterHelper.toUrl(getContext(), link.link);
            }
        });

        if (mCountDown != null) {
            mCountDown.stop();
        }

        mCountDown = new CountDown(
            (TextView) findViewById(R.id.count_down_d),
            (TextView) findViewById(R.id.count_down_h),
            (TextView) findViewById(R.id.count_down_m),
            (TextView) findViewById(R.id.count_down_s)
        );
        mCountDown.count(product.timeend * 1000 - System.currentTimeMillis());

        FrescoImageView iv = v.findViewById(R.id.product_img);
        iv.loadView(product.img);

        TextView title = v.findViewById(R.id.product_name);
        title.setText(product.title);

        DecimalFormat format = new DecimalFormat("#0.00");

        TextView price = v.findViewById(R.id.product_price);
        price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        price.setText(format.format(product.price / 100));

        TextView priceCut = v.findViewById(R.id.product_price_cut);
        priceCut.setText(format.format(product.salePrice / 100));
    }

    public void render(int id, LinkBean link) {
        //hide countdown view
        View v = findViewById(R.id.count_down_entrance);
        v.setVisibility(GONE);

        if (link != null) {
            View.OnClickListener listener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    RouterHelper.toUrl(v.getContext(), (String) v.getTag());
                }
            };

            EntranceView view = findViewById(id);
            view.setVisibility(View.VISIBLE);
            view.setImgUrl(link.img);
            view.setTag(link.link);
            view.setOnClickListener(listener);
        }
    }

    /**
     * 倒计时管理
     */
    class CountDown {
        private final TextView d;
        private final TextView h;
        private final TextView m;
        private final TextView s;
        private CountDownTimer timer;

        CountDown(TextView d, TextView h, TextView m, TextView s) {
            this.d = d;
            this.h = h;
            this.m = m;
            this.s =s ;
        }

        void render(final int day, final int hour, final int min, final int sec) {
            d.post(new Runnable() {
                @Override
                public void run() {
                    d.setText(String.format("%02d", day));
                    h.setText(String.format("%02d", hour));
                    m.setText(String.format("%02d", min));
                    s.setText(String.format("%02d", sec));
                }
            });
        }

        void count(long duration) {
            stop();

            timer = new CountDownTimer(duration, 1000) {
                @Override
                public void onTick(long l) {
                    double total =  l / 1000 ;
                    double day = Math.floor(total / (24 * 3600));
                    double hour = Math.floor((total - day * 24 * 3600) / 3600);
                    double min = Math.floor((total - day * 24 * 3600 - hour * 3600) / 60);
                    double sec = Math.floor((total - day * 24 * 3600 - hour * 3600 - min * 60));
                    render((int) day, (int) hour, (int) min, (int) sec);
                }

                @Override
                public void onFinish() {
                    render(0, 0, 0, 0);
                }
            };
            timer.start();
        }

        void stop() {
            if (timer != null) {
                timer.cancel();
            }
        }
    }

}
